package com.suray.wcs.service.init.device;

import com.suray.basic.wcs.plc.enums.RobotStatus;
import com.suray.basic.wcs.plc.pojo.RoBotHeartSendBean;
import com.suray.basic.wcs.plc.pojo.Robot;
import com.suray.basic.wcs.utils.Coord;
import com.suray.wcs.service.system.entity.DeviceDB;
import com.suray.wcs.service.thread.RobotHeartThread;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class RobotManager {
    public final List<Robot> ROBOTS = new ArrayList<>();

    public RobotManager() {

    }

    public void createRobot(DeviceDB deviceDB) {
        Robot robot = buildRobot(deviceDB);
        ROBOTS.add(robot);
        new RobotHeartThread(robot).start();
    }

    private Robot buildRobot(DeviceDB deviceDB) {
        Robot robot = new Robot();
        BeanUtils.copyProperties(deviceDB, robot);
        robot.setStatus(RobotStatus.UNKNOWN);
        robot.setNo(deviceDB.getDeviceNo());
        RoBotHeartSendBean roBotHeartSendBean = new RoBotHeartSendBean(deviceDB.getName());
        robot.setRobotHeart(roBotHeartSendBean);
        return robot;
    }

    /**
     * 根据设备号获取机械臂对像
     *
     * @param robotNo
     * @return
     */
    public Robot getByRobotNo(String robotNo) {
        Robot returnRobot = null;
        if (robotNo == null) {
            throw new IllegalArgumentException("机械臂设备号不能为空");
        }
        for (Robot robot : ROBOTS) {
            if (robot.getNo().equals(robotNo)) {
                returnRobot = robot;
                break;
            }
        }
        if (returnRobot == null) {
            throw new IllegalStateException("找不到设备号: " + robotNo + "对应的机械臂对象");
        }
        return returnRobot;
    }

    /**
     * 根据设备编号查找设备
     * @param coord
     * @return
     */
    public Robot getRobotByCoord(Coord coord) {
        for (Robot robot : ROBOTS) {
            if (robot.getLocation().equals(coord)) {
                return robot;
            }
        }

        return null;
    }
}
